import FlexBuffer from "./flex-buffer";
import { vfmtPosUvColor } from './vertex-format';

export default function RenderData () {
    // Float32Array[] 顶点数组， index 为 mesh index
    this.vDatas = [];
    // 由 vDatas element buffer 创建的 Uint32Array
    // Uint32Array[]
    this.uintVDatas = [];
    // Uint16Array[] 顶点索引 数组
    this.iDatas = [];
    // 面数
    this.meshCount = 0;

    this._infos = null;
    this._flexBuffer = null;
}

cc.js.mixin(RenderData.prototype, {
    init (assembler) {
    },
    clear () {
        this.vDatas.length = 0;
        this.iDatas.length = 0;
        this.uintVDatas.length = 0;
        this.meshCount = 0;

        this._infos = null;

        if (this._flexBuffer) {
            this._flexBuffer.reset();
        }
    },

    updateMesh (index, vertices, indices) {
        this.vDatas[index] = vertices;
        this.uintVDatas[index] = new Uint32Array(vertices.buffer, 0, vertices.length);
        this.iDatas[index] = indices;
    
        this.meshCount = this.vDatas.length;
    },

    updateMeshRange (verticesCount, indicesCount) {
    },
    
    /**
     * 创建数据
     * @param {number} index 第几个面
     * @param {number[]} verticesFloats 顶点数量
     * @param {number} indicesCount 顶点索引数量
     */
    createData (index, verticesFloats, indicesCount) {
        let vertices = new Float32Array(verticesFloats);
        let indices = new Uint16Array(indicesCount);
        this.updateMesh(index, vertices, indices);
    },
    
    /**
     * 创建四边形数据
     * @param {number} index 第几个面
     * @param {number[]} verticesFloats 顶点数量
     * @param {number} indicesCount 顶点索引数量
     */
    createQuadData (index, verticesFloats, indicesCount) {
        this.createData(index, verticesFloats, indicesCount);
        this.initQuadIndices(this.iDatas[index]);
    },

    createFlexData (index, verticesFloats, indicesCount, vfmt) {
        vfmt = vfmt || vfmtPosUvColor;
        this._flexBuffer = new FlexBuffer(this, index, verticesFloats, indicesCount, vfmt);
    },

    /** 四边形索引 */
    initQuadIndices(indices) {
        // 每个四边形由4个顶点，组成2个三角形
        // 第一个三角形 索引 0, 1, 2
        // 第一个三角形 索引 1, 3, 2

        //  2   3
        //  0   1
        let count = indices.length / 6;
        for (let i = 0, idx = 0; i < count; i++) {
            let vertextID = i * 4;
            indices[idx++] = vertextID;
            indices[idx++] = vertextID+1;
            indices[idx++] = vertextID+2;
            indices[idx++] = vertextID+1;
            indices[idx++] = vertextID+3;
            indices[idx++] = vertextID+2;
        }
    }
})

cc.RenderData = RenderData;

